<template>
  <j-modal
    :title="'1688' + (parentId ? '子' : '主') + '账号授权' + (editId ? '编辑' : '新增')"
    :width="800"
    :visible.sync="modalVisible"
    :maskClosable="false"
    switchFullscreen
  >
    <a-spin :spinning="submitLoading">
      <a-alert type="warning" banner show-icon style="margin-bottom: 10px">
        <template #description>
          <div v-if="parentId">
            当前页面仅支持选中的1688账号下的<span style="font-weight: bold">子账号授权</span>，点击查看 <a>详细操作</a>
          </div>
          <div v-else>
            当前页面仅支持1688<span style="font-weight: bold">主账号授权</span>，点击查看 <a>详细操作</a>
          </div>
        </template>
      </a-alert>
      <a-form-model ref="form" :model="formData" :rules="rules">
        <template v-if="parentId">
          <a-form-model-item label="所属主账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
            {{ parentMsg }}
          </a-form-model-item>
          <a-form-model-item label="选择账号" prop="platformAccountId" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select v-model="formData.platformAccountId" :disabled="editId">
              <a-select-option v-for="item in accountList" :key="item.subUserId" :value="item.subUserId">
                {{ item.subUserId }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </template>
        <a-form-model-item label="账号名称" prop="name" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-model="formData.name" placeholder="需保持系统内唯一，添加后不可修改" :maxLength="50" />
        </a-form-model-item>
        <a-form-model-item label="使用人" prop="holderUsers" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-url-select
            v-model="formData.holderUsers"
            :multiple="true"
            placeholder="请选择账户使用人，搜索下拉匹配，可多选"
            optionLabel="username"
            url="/sys/user/getAllUsernameByOrg"
          />
        </a-form-model-item>
        <a-form-model-item label="授权" prop="authId" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-button type="primary" :loading="submitLoading" @click="authClick">点击授权</a-button>
          <span style="margin-left: 10px;color: #fa8c16;">注：点击授权后将跳转到1688网站后台授权。</span>
        </a-form-model-item>
        <a-form-model-item label="使用状态" prop="enableStatus" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-model="formData.enableStatus">
            <a-radio value="Y">启用</a-radio>
            <a-radio value="N">停用</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea v-model="formData.remark" rows="4" placeholder="请输入备注" :maxLength="128" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit"> 保存 </a-button>
    </template>
  </j-modal>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import { randomUUID } from '@/utils/util'

export default {
  props: {
    // 要编辑的id，为空表示新增
    editId: {
      type: String,
      default: '',
    },
    // 主账号id，存在表示编辑的是子账号
    parentId: {
      type: String,
      default: '',
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      submitLoading: false,
      parentMsg: '',
      formData: {
        platformAccountId: '',
        name: '', // 名称
        holderUsers: '',
        enableStatus: 'Y',
        remark: '',
        authId: '', // 授权id，前端生成的唯一id，用于服务端建立系统内的授权与1688授权的关系
      }, // 表单数据

      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        add: `/hzkj-purchase/purchase/auth/account/add`,
        edit: `/hzkj-purchase/purchase/auth/account/edit`,
        queryById: `/hzkj-purchase/purchase/auth/account/queryById`,
        getAuthUrl: `/hzkj-purchase/purchase/auth/account/getAuthUrl`,
        getSubAccount: `/hzkj-purchase/purchase/auth/account/getSubAccount`,
      },
      accountList: [],
    }
  },
  computed: {
    rules() {
      return {
        platformAccountId: [{ required: !!this.parentId, message: '请选择账号!' }],
        name: [{ required: true, message: '请输入账号名称!' }],
        holderUsers: [{ required: true, message: '请选择使用人!' }],
        authId: [{ required: true, message: '请点击并授权' }],
      }
    },
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    authClick() {
      if (!this.formData.authId) {
        // 新增，前端创建一个唯一id
        this.formData.authId = randomUUID() + new Date().getTime()
      }
      this.submitLoading = true
      getAction(this.url.getAuthUrl, { authId: this.formData.authId }).then((res) => {
        if (res.success) {
          this.submitLoading = false
          window.open(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getSubAccount(id) {
      getAction(this.url.getSubAccount, { id }).then((res) => {
        if (res.success) {
          this.accountList = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          let request = this.editId ? putAction : postAction
          request(this.editId ? this.url.edit : this.url.add, this.formData)
            .then((res) => {
              if (res.success) {
                this.$message.success('操作成功')
                this.$emit('submit')
                this.modalVisible = false
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },
  },
  created() {
    // 俩id都没表示新增主账号
    // 有editId表示编辑账号
    // 有parentId表示新增子账号
    if (this.editId || this.parentId) {
      // 编辑，需要回显
      this.submitLoading = true
      getAction(this.url.queryById, { id: this.editId || this.parentId }).then((res) => {
        if (res.success) {
          if (this.editId) {
            this.formData = res.result
          }
          if (this.parentId) {
            this.parentMsg = `${res.result.name}[${res.result.platformAccountId}]`
          }
          this.submitLoading = false
        } else {
          this.$message.warning(res.message)
        }
      })
    }
    if (this.parentId) {
      this.getSubAccount(this.parentId)
    }
  },
}
</script>
